;(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        factory(jQuery);
    }
}(function ($) {
        $.fn.exam = function (options) {
            var defaults = {
                'room': {},
                'page': {},
                'url': ''
            };
            var self = this;
            var $this = $(this);
            var start = new Date().getTime();

            this.settings = $.extend(defaults, options);

            if (self.settings.room.start != 0 && start > (Date.parse(self.settings.room.time) - self.settings.room.start * 60)) {
                alert("已经超过入场时间");
                window.history.go(-1);
            }

            var _init = function () {

                $('#testTitle').html(self.settings.page['title']);

                var m = self.settings.page['time'] * 60;

                setInterval(function () {
                    if (m >= 0) {
                        var hours = Math.floor(m / (60 * 60));
                        var minutes = Math.floor(m % (60 * 60) / 60) < 10 ? '0' + Math.floor(m % (60 * 60) / 60) : Math.floor(m % (60 * 60) / 60);
                        var seconds = (m % (60 * 60)) % 60 < 10 ? '0' + (m % (60 * 60)) % 60 : (m % (60 * 60)) % 60;
                        $('#testTime').html(hours + ":" + minutes + ":" + seconds);
                        --m;
                    } else {
                        $('#testForm').submit();
                    }
                }, 1000);


                $.each($.parseJSON(self.settings.page.question), function (type, k) {
                    _loadQuestion(type, k.n, self.settings.page.category)
                });

            };

            var _cover = function (close) {
                if (close) {
                    $('#cover').remove();
                    $('#loading').remove();
                } else {
                    $('body').append(
                        $('<div>', {'id': 'cover'}).css({
                            'position': 'absolute',
                            'left': '0px',
                            'top': '0px',
                            'background': 'rgba(0, 0, 0, 0.4)',
                            'width': '100%',
                            'height': '100%',
                            'filter': 'alpha(opacity=60)',
                            'opacity': '0.6',
                            'display': 'block',
                            'z-Index': '1030'
                        })
                    ).append(
                        $('<div>', {'id': 'loading'}).css({
                            'position': 'absolute',
                            'width': '500px',
                            'height': '30px',
                            'top': '40%',
                            'left': '40%',
                            'color': '#fff',
                            'display': 'block',
                            'cursor': 'pointer',
                            'z-Index': '1031'
                        }).html("<i class='icon-spin4 animate-spin'></i> 正在加载试卷，请稍等...")
                    )
                }
            };

            var _loadQuestion = function (type, num, category) {
                var title, input, icon, an;
                switch (parseInt(type)) {
                    case 1:
                        title = "单选题";
                        input = "radio";
                        icon = "fa-check-circle-o";
                        break;
                    case 2:
                        title = "多选题";
                        input = "checkbox";
                        icon = " fa-check-square-o";
                        break;
                    case 3:
                        title = "判断题";
                        input = "radio";
                        icon = "fa-times-circle-o";
                        an = ['正确', '错误'];
                        break;
                    case 4:
                        title = "填空题";
                        input = "text";
                        icon = "fa-check-circle-o";
                        break;
                    case 5:
                        title = "问答题";
                        input = "textarea";
                        icon = "fa-check-circle-o";
                        break;
                }
                var menu = _buildMenu(title, type, icon, num);
                $("#testMenu").append(menu);

                var exam_start = _store('exam_start_' + self.settings.room.id);
                var exam_data = _store("page_" + self.settings.page.id + '_' + type);

                $this.append("<div class=\"well well-sm\"><h4>" + title + "</h4></div>");

                if (!exam_start
                    || self.settings.room.start == 0
                    || start > (Date.parse(self.settings.room.time) - 60 * 60)
                    || !exam_data
                ) {
                    _store('exam_start_' + self.settings.room.id, start);

                    $.ajax({
                        url: self.settings.url,
                        type: "post",
                        async: false,
                        data: {
                            type: type,
                            num: num,
                            category: category,
                            upset: self.settings.page.upset
                        },
                        success: function (data) {
                            exam_data = data;
                            _store("page_" + self.settings.page.id + '_' + type, data);
                        }
                    });
                }

                $.each($.parseJSON(exam_data), function (v, k) {
                    var question = _buildQuestion(k, type, v + 1);
                    $this.append(question)
                })

            };

            var _buildMenu = function (title, type, icon, num) {
                var menu = $('<li>').append($('<a>', {'href': '#'}).html('<i class="fa ' + icon + '"></i> <span>' + title + '</span>'))
                    .append($('<ul>', {'style': 'padding: 5px;'}));
                var table = $('<table>', {'class': "table table-condensed text-center"}).append($("<tr>"));

                for (var i = 1; i <= num; i++) {
                    if (i % 5 == 1) table.append($("<tr>"))
                    table.find("tr:last").append($("<td>").html('<a href="#question_' + type + '_' + i + '" class="question">' + i + '</a>'))
                }

                menu.children('ul').append(table);
                return menu;
            };

            var _buildQuestion = function (question, type, id) {
                var input, an;
                switch (parseInt(type)) {
                    case 1:
                        input = "radio";
                        break;
                    case 2:
                        input = "checkbox";
                        break;
                    case 3:
                        input = "radio";
                        an = ['正确', '错误'];
                        break;
                    case 4:
                        input = "text";
                        break;
                    case 5:
                        input = "textarea";
                        break;
                }
                var questionBox = $('<div class="box box-primary " id="question_' + type + '_' + id + '">\n' +
                    '                <div class="box-header with-border">\n' +
                    '                <h3 class="box-title" style="margin: 0 20px 0 0;">' + id + "、" + question.title + '</h3>\n' +
                    '<div class="box-tools pull-right"><button type="button" class="btn btn-box-tool flag"><i class="fa fa-flag-o"></i></button></div>' +
                    '            </div>\n' +
                    '            <div class="box-body">\n' +
                    '               <ol type="A" class="options"></ol>' +
                    '            </div>\n' +
                    '        </div>');
                $.each($.parseJSON(question['option']), function (k, v) {
                    var option = $("<li>");

                    if (type == 5) {
                        option.append("<textarea name='answer[" + id + "][" + question.id + "]'>></textarea>")
                    } else {
                        option.append("<label><input type=\"" + input + "\" name=\"answer[" + id + "][" + question.id + "][]\" value=\"" + k + "\"/> " + v.t + "</label>")
                    }
                    questionBox.find('.box-body ol').append(option)
                });
                return questionBox;

            }

            var _store = function () {
                if (typeof(arguments[0]) == 'object') {
                    arguments[0].each(function (name, val) {
                        localStorage.setItem(name, val);
                    })
                } else if (arguments[1]) {
                    localStorage.setItem(arguments[0], arguments[1]);
                } else {
                    return localStorage.getItem(arguments[0]);
                }
            };

            var _bindKey = function () {
                $(document).keydown(function (event) {
                    if ((event.altKey) && ((event.keyCode == 37) || event.keyCode == 39 || event.keyCode == 115)) { //屏蔽 Alt+ 方向键 ← ,屏蔽 Alt+ 方向键 →.alt+f4
                        event.returnValue = false;
                        return false;
                    } else if (event.keyCode == 8 || event.keyCode == 116 || event.keyCode == 27 || event.keyCode == 122) {//屏蔽退格删除键屏蔽F5 f11刷新键
                        event.returnValue = false;
                        return false;
                    } else if (event.ctrlKey && (event.keyCode == 82 || event.keyCode == 87 || event.keyCode == 78 || event.keyCode == 67 || event.keyCode == 86)) {//屏蔽Ctrl + R  Ctrl+n Ctrl+w
                        event.returnValue = false;
                        return false;
                    } else if (event.shiftKey && event.keyCode == 121) {
                        event.returnValue = false;
                        return false;
                    }
                });

                $this.on('change', 'input,textarea', function () {
                    var id = $(this).parents('div.box:first').attr('id');
                    var a=$('#testMenu').find('a[href="#' + id + '"]');
                    a.addClass('active');
                    if (!a.parents('li:first').hasClass('active')) {

                        a.parents('li:first').find('a:first').click();

                    }
                });

                $this.on('click', '.flag', function () {
                    var id = $(this).parents('div.box:first').attr('id');
                    $(this).toggleClass('bg-yellow').find('i').toggleClass('fa-flag-o fa-flag-checkered');
                    if ($('#testMenu').find('a[href="#' + id + '"]').find(".badge").length == 0) {
                        $('#testMenu').find('a[href="#' + id + '"]').append('<span class="badge bg-yellow"><i class="fa fa-flag-checkered"></i> </span>')
                    } else {
                        $('#testMenu').find('a[href="#' + id + '"]').find(".badge").remove();
                    }
                })

            };

            _init();
            _bindKey();
            setTimeout(_cover(true), 5000);
            $('#testMenu').find('li:eq(1)').addClass('active');
            $('#testMenu').metisMenu({});
            return this;
        }
    }
));

document.body.onselectstart = function () {
    return false;
};

